package com.tkc.controller.util;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.tkc.common.enums.BaseResultCodeEnum;
import com.tkc.common.exception.ResponseException;
import com.tkc.common.result.CommonResult;

/**
 * 
 * @Function:控制层异常检查和捕获
 * 
 * @Project :assessmenttask 
 * @Package :com.tkc.controller.util 
 * @File :ControllerErrorProcessor.java 
 * @ClassName: ControllerErrorProcessor  
 * 
 * @author tankaichao 
 * @email cgztkc@126.com 
 * @Date 2016年8月9日下午5:56:15
 * @since JDK 1.8 
 *
 */
public class ControllerErrorProcessor {
    /**
     * 入参异常检查
     * @param resultList
     * @param errorParams 需要捕获的错误码
     */
    public static void paramErrorProcessor(BindingResult resultList, String... errorParams) {
        List<String> errorParamList = new ArrayList<String>();
        for (String errorParam : errorParams) {
            errorParamList.add(errorParam);
        }
        if (resultList.hasErrors()) {
            List<ObjectError> errorList = resultList.getAllErrors();
            for (ObjectError error : errorList) {
                if (errorParamList.contains(error.getDefaultMessage()))
                    throw new ResponseException(BaseResultCodeEnum.valueOf(error
                        .getDefaultMessage()));
            }
        }
    }

    public static CommonResult exceptionProcessor(Exception ex, Logger logger) {
        if (ex instanceof ResponseException) {
            ResponseException re = (ResponseException) ex;
            logger.warn("操作失败:" + re.getExceptionEnums().toString());
            return ResponseException.buildException(re);
        } 
        else {
            logger.error("系统异常:" + ex.getMessage());
            return ResponseException.buildException(new ResponseException(
                BaseResultCodeEnum.ERR_CODE_00000));
        }
    }
}
